﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Aliyun.OSS;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace BCGM.MedicalWisdom.Common.AliYun
{
    public class AliYunOSSHelper
    {
        private ILogger<AliYunOSSHelper> _logger;


        /// <summary>
        /// 阿里云帮助类
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="configHelper"></param>
        public AliYunOSSHelper(ILogger<AliYunOSSHelper> logger)
        {

            _logger = logger;

        }


        /// <summary>
        /// 阿里云上传底层方法，文件为IFormFile
        /// </summary>
        /// <param name="shop_code"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        public async Task<List<string>> AliYunUpLoad(List<IFormFile> files)
        {
            List<string> ossfilesNameList = new List<string>();
            try
            {

                //阿里云oss相关参数,请自行补齐 
                var endpoint = "oss-cn-shanghai.aliyuncs.com";
                var accessKeyId = "LTAI5tQR4xfuXTiNLPNrR3sh";
                var accessKeySecret = "6ILhhzSf0DYhStkPxCyZEHddQEBa4f";
                var bucket = "bcgmbutket";
                var imageUrl = "";

                var write_client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                var read_client = new OssClient(endpoint, accessKeyId, accessKeySecret);

                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i];
                    var fname = DateTime.Now.ToString("yyyyMMddHHmmssffffff") + i + Path.GetExtension(file.FileName);
                    using (var stream = file.OpenReadStream())
                    {
                        write_client.PutObject(bucket, fname, stream);
                    }
                    DateTime expiration = DateTime.Now.AddYears(20);
                    var url = read_client.GeneratePresignedUri(bucket, fname, expiration);
                    //string urlstring = imageUrl + url.AbsolutePath;
                    string urlstring = url.AbsolutePath;
                    ossfilesNameList.Add(urlstring);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "阿里云图片上传失败,ex=" + ex.Message);
                throw;
            }

            return ossfilesNameList;
        }

    }
}
